import $store from '@/store'
import uni_request from '@/utils/uni_request/uni_request.js'
import {baseURL,isEmpty} from '@/utils/util.js'
import { getSign } from './signUtils';
import JSEncrypt from 'jsencrypt';
import { md5 } from 'js-md5';

const request = uni_request({
	baseURL
})

let postDelayTask = null;
let timer = null;
const postWithDelay = function(url, data, delay, fn) { // post防抖方法
	postDelayTask && postDelayTask.abort();
	if (timer) {
	  clearTimeout(timer);
	}
	timer = setTimeout(() => {
	  postDelayTask = request.post(url, data);
	  postDelayTask.then(res => fn(res));
	}, delay);
}

request.interceptors.request.use(async (config, ...args) => { // 请求拦截器
	return new Promise((resolve, reject) => {
		config.header['content-type'] = "application/json"
		config.header['X-App-Source'] = "applet"
		config.header['X-Access-Token'] = uni.getStorageSync('token');  // 把 token 放在请求头
		getSign(config.method, config.url, config.data).then(sign => {
			config.header["X-SIGN"] = sign
			resolve(config)
		}) 
	})
})

request.interceptors.response.use(async (res, ...args) => { // 响应拦截器
	let apiFail = true;
	switch (res.statusCode) {
		case 401:
			uni.hideLoading();
			if(args[1]!=='/login/wechat/phone'&&args[1]!=='/login/wechat/auto')
			{
				uni.setStorageSync('needLogin',true);
				uni.setStorageSync('unAuthApi',args[1]);
				uni.showToast({
					title: '需要登录',
					icon: "none",
					duration: 1000
				});
				setTimeout(()=>{
					uni.switchTab({
					    url: "/pages/index/index",
						// success: function (e) {
						//    let page = getCurrentPages().pop();
						//    if (page === undefined || page === null) return;
						//    page.onLoad();
						// }
					})
				},1000);
			}
			break;
		case 200:
		    if(res.data.code!=='00000000')
			{
				uni.showToast({
					title: res.data.message || '出错了',
					icon: "none",
					duration: 2000
				});
			}
			else
			{
				apiFail=false;
			}
			break;
		default:
			uni.showToast({
				title: res.data.message || '出错了',
				icon: "none",
				duration: 2000
			});
			break;
	}
	if(!apiFail)
	{
	   return res
	}
})

request.onerror = (...args) => {
	//console.log(args) // 错误监听
}

export default request
